#!/bin/bash

# iTerm 跳转到 Finder 脚本
# 获取当前 iTerm 窗口的工作目录并在 Finder 中打开

get_iterm_path() {
    # 方法1: 尝试获取 iTerm 当前会话路径
    local path=$(osascript -e '
    tell application "iTerm"
        if (count of windows) > 0 then
            tell current session of current window
                set pwd_result to (do shell script "pwd")
                return pwd_result
            end tell
        else
            return ""
        end if
    end tell
    ' 2>/dev/null)
    
    # 如果获取失败，使用默认路径
    if [ -z "$path" ] || [ "$path" = "missing value" ]; then
        path="$HOME"
    fi
    
    echo "$path"
}

open_in_finder() {
    local target_path="$1"
    
    osascript -e "
    tell application \"Finder\"
        activate
        try
            open POSIX file \"$target_path\"
        on error
            open home
        end try
    end tell
    "
}

# 主执行逻辑
main() {
    local current_path=$(get_iterm_path)
    echo "当前 iTerm 路径: $current_path"
    
    open_in_finder "$current_path"
    echo "已在 Finder 中打开: $current_path"
}

main "$@"